import { ref } from "vue"
import service from "@/axios"
import { useRouter } from 'vue-router';

export default function () {
    let user = ref({
        id: "",
        phone: "",
        password: "",
        name: "",
        address: "",
        score: "",
        status: "",
    });

    let users = ref([]);

    const router = useRouter();

    async function getAllUsers() {
        try {
            const response = await service.get('/users');
            users.value = response.data.data;
        } catch (error) {
            console.error(error);
        }
    }

    async function blockUser(userId) {
        try {
            const userIndex = users.value.findIndex(user => user.id === userId);
            if (userIndex === -1) return; // 如果用户未找到，退出

            const isBlocked = users.value[userIndex].status; // 获取当前封禁状态
            const action = isBlocked ? 'unblock' : 'block'; // 根据当前状态确定操作
            let response;
            if (action == 'block') {
                response = await service.post(`/blockUser?userId=${userId}`);
            } else {
                response = await service.post(`/freeUser?userId=${userId}`);
            }
            alert(response.data.msg);

            await getAllUsers();
        } catch (error) {
            console.error(error);
        }
    }

    async function adminlogin() {
        await service.post('/login', {
            phone: user.value.phone,
            password: user.value.password,
        }).then(response => {
            if (response.data.code == 200) {
                alert(response.data.msg);
                localStorage.setItem("loginUser", JSON.stringify(response.data.data));
                router.push('/admin');
            } else {
                alert(response.data.msg);
            }
        }).catch(error => {
            console.error(error);
        });
    }


    async function login() {
        await service.post('/login', {
            phone: user.value.phone,
            password: user.value.password,
        }).then(response => {
            if (response.data.code == 200) {
                alert(response.data.msg);
                localStorage.setItem("loginUser", JSON.stringify(response.data.data));
                if (localStorage.getItem('public') === null) {
                    localStorage.setItem('public', false);
                }
                router.push('/mainPage');
            } else {
                alert(response.data.msg);
            }
        }).catch(error => {
            console.error(error);
        });
    }

    async function register() {
        await service.post('/register', {
            phone: user.value.phone,
            password: user.value.password,
            // name: user.value.name,
            // address: user.value.address
        }).then(response => {
            if (response.data.code == 200) {
                alert(response.data.msg);
                login()
            } else {
                alert(response.data.msg);
            }
        }).catch(error => {
            console.error(error);
        });
    }

    async function userVote(matchId, win) {
        console.log(JSON.parse(localStorage.getItem("loginUser")).id);
        await service.post('/vote', {
            userId: JSON.parse(localStorage.getItem("loginUser")).id,
            matchId: matchId,
            win: win
        }).then(response => {
            if (response.data.code == 200) {
                localStorage.setItem("loginUser", JSON.stringify(response.data.data));
                alert(response.data.msg);
            } else {
                alert(response.data.msg);
            }
        }).catch(error => {
            console.error(error);
        });
    }

    async function updateUser(userName, userAddress) {
        await service.post('/updateUser', {
            id: JSON.parse(localStorage.getItem("loginUser")).id,
            name: userName,
            address: userAddress
        }).then(response => {
            if (response.data.code == 200) {
                localStorage.setItem("loginUser", JSON.stringify(response.data.data.data));
                alert(response.data.msg);
            } else {
                alert(response.data.msg);
            }
        }).catch(error => {
            console.error(error);
        });
    }

    return {
        user,
        users,
        getAllUsers,
        blockUser,
        login,
        register,
        userVote,
        updateUser,
        adminlogin
    }
}
